# -*- mode: python ; coding: utf-8 -*-

import os
import hashlib
import urllib
import requests
import random
import json

import time



class Util(object):

    def __init__(self):

        self.icon_path = os.path.join(os.getcwd(), 'icon.ico')
        self.lang = {
            "自动检测": "auto","中文": "zh","英语": "en","粤语": "yue","文言文": "wyw",
            "日语": "jp","韩语": "kor","法语": "fra","西班牙语": "spa","泰语": "th",
            "阿拉伯语": "ara","俄语": "ru","葡萄牙语": "pt","德语": "de","意大利语": "it",
            "希腊语": "el","荷兰语": "nl","波兰语": "pl","保加利亚语": "bul","爱沙尼亚语": "est",
            "丹麦语": "dan","芬兰语": "fin","捷克语": "cs","罗马尼亚语": "rom","斯洛文尼亚语": "slo",
            "瑞典语": "swe","匈牙利语": "hu","繁体中文": "cht","越南语": "vie"
            }
        

    def do_translate(self, comboBoxTo_text, comboBoxFrom_text, input_text):
     
        secretkey = '0bZL7gh_JfBb3hhk4p6m'
        md5 = hashlib.md5()
        salt = str(random.randint(0,99))
        appid = "20190110000256011"
        md5.update(bytes(appid + input_text + salt + secretkey, encoding='utf-8'))
        sign = md5.hexdigest()

        form_data = {
            'q': input_text,
            'from': comboBoxFrom_text,
            'to': comboBoxTo_text,
            'appid': appid,
            'salt': salt,
            'sign': sign
        }

        # 请求翻译文本
        base_url = 'https://fanyi-api.baidu.com/api/trans/vip/translate?'
     
        resp_url = base_url + urllib.parse.urlencode(form_data)
        resp = requests.get(resp_url)
        return resp



    def fetch_token(self):

        APP_KEY = "ba23vwF1u8luK1zaIfhhlcEe"
        SECRET_KEY = "lIFGt4sDDvb1iZGHMPGtrAf1jFaaSGnG"
        TOKEN_URL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APP_KEY+"&client_secret="+SECRET_KEY

        try:
            token_resp = requests.get(TOKEN_URL)
           
        except Exception as e:
            return 'error'
            
    
        token = json.loads(token_resp.text)["access_token"] 

        time_stamp = str(int(time.time()))
       
        with open('TOKEN.txt','w',encoding="utf-8") as f:
            f.write(str(time_stamp+"\t"+token))


        with open('TOKEN.txt','r',encoding="utf-8") as f:
            str_token = f.read()

            return str_token



    def sound(self,text):

 


        if not text:
            return

        time_stamp_now = int(time.time())

        token_info = ''

        if not os.path.exists("TOKEN.txt"):
            self.fetch_token()


        with open('TOKEN.txt','r',encoding="utf-8") as f:
            token_info = f.read()

        time_stamp_old = int(token_info.split("\t")[0])
        token = token_info.split("\t")[1]


        if time_stamp_now - time_stamp_old >= 2419200: # 28天
            token_info = self.fetch_token()

            with open('TOKEN.txt','r',encoding="utf-8") as f:
                token_info = f.read()
                token = token_info.split("\t")[1]



        tex = urllib.parse.quote_plus(text)

        # 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，
        # 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 
        PER = 0
        # 语速，取值0-15，默认为5中语速
        SPD = 5
        # 音调，取值0-15，默认为5中语调
        PIT = 5
        # 音量，取值0-9，默认为5中音量
        VOL = 5
        # 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
        AUE = 3

        FORMATS = {3: "mp3", 4: "pcm", 5: "pcm", 6: "wav"}
        FORMAT = FORMATS[AUE]

        CUID = "gogogo123321"


        params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,
              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数

        TTS_URL = 'https://tsn.baidu.com/text2audio?'
        # url_params = urlencode(params)
        # print(TTS_URL + url_params)
        try:
            response = requests.post(url=TTS_URL, data=params, timeout=10)
            
        except Exception as e:
            return 'error'

        if response.headers["Content-Type"].startswith('application/json'):
            return "error"

        with open('voice_file.mp3','wb') as f:
            f.write(response.content)

        return 'succeed'